import { defineStore } from 'pinia'
import { CartType } from '@/types/cart'
import { SkuType } from '@/types/goods'
// import { GoodsType } from '@/types/goods'
import userStore from './user'
import {
  getNewCartGoods,
  mergeLocalCart,
  findCartList,
  insertCart,
  deleteCart,
  updateCart,
  checkAllCart
} from '@/api/cart'
import store from '../store'

const user = userStore(store)
// 购物车状态
const cartStore = defineStore({
  id: 'cartStore',
  state: () => ({
    list: [] as CartType[]
  }),
  actions: {
    insertCart(goods: CartType) {
      const sameIndex = this.list.findIndex(item => item.skuId === goods.skuId)
      // 逻辑: 有相同的给 goods 累加数量 删除相同 skuId 的商品
      if (sameIndex >= 0) {
        goods.count = this.list[sameIndex].count + goods.count
        this.list.splice(sameIndex, 1)
      }
      this.list.unshift(goods)
    },
    insertCartAsync(goods: CartType) {
      return new Promise<void>(resolve => {
        if (user.user.token) {
          // 已
          insertCart(goods.skuId, goods.count)
            .then(() => {
              return findCartList()
            })
            .then(res => {
              this.setCartList(res.data.result)
              resolve()
            })
        } else {
          // 未登录
          this.insertCart(goods)
          resolve()
        }
      })
    },
    // 修改购物车商品
    updateCart(goods: CartType) {
      // goods中字段有可能不完整
      const updateGoods = this.list.find(item => item.skuId === goods.skuId)
      for (const key in goods) {
        if (
          goods[key] !== null &&
          goods[key] !== undefined &&
          goods[key] !== ''
        ) {
          updateGoods[key] = goods[key]
        }
      }
    },
    // 修改购物车商品
    updateCartAsync(goods: CartType) {
      return new Promise<void>(resolve => {
        if (user.user.token) {
          // 登录TODO
          updateCart(goods)
            .then(() => {
              return findCartList()
            })
            .then(res => {
              this.setCartList(res.data.result)
              resolve()
            })
        } else {
          // 本地
          this.updateCart(goods)
          resolve()
        }
      })
    },
    // 获取购物车列表
    findCartList() {
      return new Promise<void>((resolve, reject) => {
        if (user.user.token) {
          // 登录TODO
          findCartList().then(res => {
            this.setCartList(res.data.result)
            resolve()
          })
        } else {
          // 本地
          // 传参数promise数组
          const promiseArr = this.list.map(item => {
            // 返回接口函数的调用
            return getNewCartGoods(item.skuId)
          })
          Promise.all<any>(promiseArr)
            .then(dataArr => {
              dataArr.forEach((res, i) => {
                this.updateCart({
                  skuId: this.list[i].skuId,
                  ...res.data.result
                })
              })
              resolve()
            })
            .catch(e => {
              reject(e)
            })
        }
      })
    },
    // 删除购物车商品
    deleteCart(skuId: string) {
      const index = this.list.findIndex(item => item.skuId === skuId)
      this.list.splice(index, 1)
    },
    deleteCartAsync(skuId: string) {
      return new Promise<void>(resolve => {
        if (user.user.token) {
          // 登录TODO
          deleteCart([skuId])
            .then(() => {
              return findCartList()
            })
            .then(res => {
              this.setCartList(res.data.result)
              resolve()
            })
        } else {
          // 本地
          this.deleteCart(skuId)
          resolve()
        }
      })
    },
    // 有效商品 全选反选
    checkAllCart(selected: boolean) {
      return new Promise<void>(resolve => {
        if (user.user.token) {
          // 登录TODO
          const ids = this.validList.map(item => item.skuId)
          checkAllCart(selected, ids)
            .then(() => {
              return findCartList()
            })
            .then(res => {
              this.setCartList(res.data.result)
              resolve()
            })
        } else {
          // 本地
          this.validList.forEach(item => {
            this.updateCart({ ...item, selected })
          })
          resolve()
        }
      })
    },
    // 批量删除选中商品
    batchDeleteCart(isClear: boolean) {
      return new Promise<void>(resolve => {
        if (user.user.token) {
          // 登录TODO
          // 得到需要删除的商品列表的skuId的集合
          const ids = this[isClear ? 'invalidList' : 'selectedList'].map(
            item => item.skuId
          )
          deleteCart(ids)
            .then(() => {
              return findCartList()
            })
            .then(res => {
              this.setCartList(res.data.result)
              resolve()
            })
        } else {
          // 本地
          this[isClear ? 'invalidList' : 'selectedList'].forEach(item => {
            this.deleteCart(item.skuId)
          })
          resolve()
        }
      })
    },
    // 修改sku规格函数
    updateCartSku(oldSkuId: string, newSku: SkuType) {
      return new Promise<void>(resolve => {
        if (user.user.token) {
          // 登录TODO
          // 1.获取原先商品的数量
          const oldGoods = this.list.find(item => item.skuId === oldSkuId)
          // 2.删除原先商品
          deleteCart([oldSkuId])
            .then(() => {
              return insertCart(newSku.skuId, oldGoods.count)
            })
            .then(() => {
              // 获取修改的skuId 和 原先商品数量 做一个加入购物车的操作
              return findCartList()
            })
            .then(res => {
              // 更新列表
              this.setCartList(res.data.result)
            })
          findCartList().then(res => {
            this.setCartList(res.data.result)
            resolve()
          })
        } else {
          // 本地
          // 1.获取旧的商品信息
          const oldGoods = this.list.find(item => item.skuId === oldSkuId)
          // 2.删除旧的商品
          this.deleteCart(oldSkuId)
          // 3.合并一条新的商品信息
          const {
            skuId,
            price: nowPrice,
            inventory: stock,
            specsText: attrsText
          } = newSku
          const newGoods = { ...oldGoods, skuId, nowPrice, stock, attrsText }
          // 4.去插入即可
          this.insertCart(newGoods)
          resolve()
        }
      })
    },
    // 设置购物车列表
    setCartList(list: CartType[]) {
      this.list = list
    },
    // 合并本地购物车
    async mergeCart() {
      // 存储token后调用合并API接口函数进行购物合并
      const cartList = this.validList.map(({ skuId, selected, count }) => {
        return { skuId, selected, count }
      })
      await mergeLocalCart(cartList)
      // 合并成功将本地购物车删除
      this.setCartList([])
    }
  },
  getters: {
    // 有效商品列表
    validList(state) {
      return state.list.filter(item => item.stock > 0 && item.isEffective)
    },
    // 有效商品件数
    validTotal(): number {
      return this.validList.reduce((p, c) => p + c.count, 0)
    },
    // 有效商品总金额
    validAmount(): number | string {
      return (
        this.validList.reduce((p, c) => p + c.nowPrice * 100 * c.count, 0) / 100
      )
    },
    // 无效商品列表
    invalidList(state): CartType[] {
      return state.list.filter(item => !(item.stock > 0 && item.isEffective))
    },
    // 选中商品列表
    selectedList(): CartType[] {
      return this.validList.filter(item => item.selected)
    },
    // 选中的商品件数
    selectTotal(): number {
      return this.selectedList.reduce((p, c) => p + c.count, 0)
    },
    // 选中商品总金额
    selectedAmount(): number {
      return (
        this.selectedList.reduce((p, c) => p + c.nowPrice * 100 * c.count, 0) /
        100
      )
    },
    // 是否全选
    isCheckAll(): boolean {
      return (
        this.validList.length === this.selectedList.length &&
        this.selectedList.length !== 0
      )
    }
  },

  persist: {
    enabled: true,
    strategies: [
      {
        key: 'cart',
        storage: localStorage,
        paths: ['list']
      }
    ]
  }
})

export default cartStore
